import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';

// 配置API基础URL（根据实际情况修改）
// 模拟器使用: http://localhost:38521/api (Android模拟器用 http://10.0.2.2:38521/api)
// 真机使用: http://你的电脑IP:38521/api (在cmd运行 ipconfig 查看IPv4地址)
const API_BASE_URL = 'http://localhost:38521/api'; // 改为你的后端IP

const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 10000
});

// 请求拦截器
api.interceptors.request.use(
  async (config) => {
    const token = await AsyncStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    if (error.response?.status === 401) {
      await AsyncStorage.removeItem('token');
      await AsyncStorage.removeItem('user');
      // 可以触发导航到登录页
    }
    return Promise.reject(error);
  }
);

// 认证API
export const authAPI = {
  login: (data) => api.post('/auth/login', data),
  register: (data) => api.post('/auth/register', data),
  getMe: () => api.get('/auth/me')
};

// 用户API
export const userAPI = {
  getBalance: (id) => api.get(`/users/${id}/balance`)
};

// 交易API
export const transactionAPI = {
  getUserTransactions: (userId, params) => 
    api.get(`/transactions/user/${userId}`, { params })
};

// 寄存酒API
export const wineAPI = {
  getUserWines: (userId, params) => 
    api.get(`/wines/user/${userId}`, { params })
};

export default api;
